package com.xzg.erp.product.web;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzg.erp.common.BusinessException;
import com.xzg.erp.common.Constants;
import com.xzg.erp.product.entity.ProductTag;
import com.xzg.erp.product.entity.dto.ProductTagDto;
import com.xzg.erp.product.service.IProductTagService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 产品标签表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2025-02-12
 */
@RestController
@RequestMapping("/productTag")
@Validated
public class ProductTagController {

    @Autowired
    private IProductTagService productTagService;

    @PostMapping("/add")
    public ResponseEntity addTag(@Valid @RequestBody ProductTag tag) {
        int loginId = StpUtil.getLoginIdAsInt();
        ProductTag one = productTagService.getOne(Wrappers.<ProductTag>lambdaQuery().eq(ProductTag::getName, tag.getName()).eq(ProductTag::getDeleted, Constants.UN_DELETED));
        if (Objects.nonNull(one)) {
            throw new BusinessException(HttpStatus.CONFLICT,Constants.DATA_EXIT);
        }
        tag.setCreatedBy(loginId);
        tag.setCreatedAt(LocalDateTime.now());
        productTagService.save(tag);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/page")
    public ResponseEntity page(@RequestBody ProductTagDto dto) {
        Page<ProductTag> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Page<ProductTag> page1 = productTagService.page(page,Wrappers.<ProductTag>lambdaQuery().eq(ProductTag::getDeleted,Constants.UN_DELETED).orderByDesc(ProductTag::getCreatedAt));
        return ResponseEntity.ok(page1);
    }

    @PostMapping("/delete/{ids}")
    public ResponseEntity delete(@PathVariable List<Integer> ids) {
        productTagService.logicDelete(ids);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/update")
    public ResponseEntity update(@RequestBody ProductTag tag) {
        int loginId = StpUtil.getLoginIdAsInt();
        tag.setUpdatedBy(loginId);
        tag.setUpdatedAt(LocalDateTime.now());
        productTagService.updateById(tag);
        return ResponseEntity.ok(Constants.SUCCESS);
    }
}
